﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;

namespace MockNetCore.Handlers
{
    public class PlaceholderHandler
    {
        private static readonly Regex pattern = new Regex(@"(@\w+)(\(.*?\))?");

        public static Object doGenerate(Options options)
        {
            String methodName = null;
            String paramStr = null;
            MatchCollection matches = pattern.Matches(options.template.ToString());
            StringBuilder sbRtn = new StringBuilder();
            bool hasFind = false;
            string template = options.template.ToString();

            for (int i = 0; i < matches.Count; i++)
            {
                hasFind = true;
                var ma1 = matches[i].Groups;

                if (matches[i].Groups.Count == 2)
                {
                    methodName = matches[i].Groups[1].Value;
                }
                else if (matches[i].Groups.Count == 3)
                {
                    methodName = matches[i].Groups[1].Value;
                    String group2 = matches[i].Groups[2].Value;
                    paramStr = group2 == null ? null : group2.Substring(1, group2.Length - 2);
                }
                try
                {
                    methodName = "_" + methodName.Substring(1);
                    Type type = typeof(_Function);
                    MethodInfo mt = type.GetMethod(methodName);
                    var result = mt.Invoke(null, new object[] { paramStr });
                    //判断下返回值，如果是数组则进行如循环
                    if (result.GetType().Equals(typeof(JArray)))
                    {
                        options.template = result;
                        return JToken.FromObject(Handler.gen(result, options.name, options.context));
                    }
                    else
                    {
                        template = pattern.Replace(template, mt.Invoke(null, new object[] { paramStr }).ToString(), 1);
                    }
                }
                catch (Exception ex)
                {
                }
            }
            return hasFind ? template : options.template;
        }
    }
}